package com.yzt.minemodule.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.sdk.android.oss.ClientException;
import com.alibaba.sdk.android.oss.ServiceException;
import com.alibaba.sdk.android.oss.model.PutObjectRequest;
import com.alibaba.sdk.android.oss.model.PutObjectResult;
import com.baidu.location.BDLocation;
import com.luck.picture.lib.basic.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.SelectMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.yzt.zhuju.RXingUtils;
import com.yzt.zhuju.arouter.RouterUser;
import com.yzt.zhuju.base.BaseActivity;
import com.yzt.zhuju.event.RxBus;
import com.yzt.zhuju.event.user.PersonalRefresh;
import com.yzt.zhuju.network.AresSubscriber;
import com.yzt.zhuju.network.biz.BizLayer;
import com.yzt.zhuju.network.entity.home.UserInfoBean;
import com.yzt.zhuju.network.entity.sysConfig.AliOSSCredentialBean;
import com.yzt.zhuju.network.entity.user.PersonEditLayoutEntry;
import com.yzt.zhuju.permission.PermissionsUtils;
import com.yzt.zhuju.utils.DefaultCropFileEngine;
import com.yzt.zhuju.utils.GlideImageEngine;
import com.yzt.zhuju.utils.ImageUpLoadUtils;
import com.yzt.zhuju.utils.McImageCompressEngine;
import com.yzt.zhuju.utils.map.BdLocationUtil;
import com.yzt.zhuju.widget.pickview.TimePickerViewManager;
import com.yzt.minemodule.R;
import com.yzt.minemodule.adapter.PersonEditLayoutAdapter;
import com.yzt.p_base.utils.DateUtils;
import com.yzt.p_base.utils.ToastUtil;
import com.yzt.plugin_imageloader.ImageLoadUtil;
import com.yzt.zhuju.widget.pickview.WhellPickerViewManager;
import com.zaaach.citypicker.CityPicker;
import com.zaaach.citypicker.adapter.OnPickListener;
import com.zaaach.citypicker.model.City;
import com.zaaach.citypicker.model.LocateState;
import com.zaaach.citypicker.model.LocatedCity;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

/**
 * author : bob
 * date   : 2022/12/8
 * desc   : 用户信息编辑
 */
@SuppressLint("SimpleDateFormat")
@Route(path = RouterUser.ACTIVITY_PERSON_DETAIL_EDIT)
public class PersonalEditActivity extends BaseActivity {

    private final int RESULT_CODE_NICKNAME = 100;

    private final int RESULT_CODE_AUTOGRAPH = 101;

    private final int RESULT_CODE_JOB = 102;

    /**
     * 头像
     */
    private ImageView imgHeader;

    /**
     * 内容设配器
     */
    private PersonEditLayoutAdapter mPersonEditLayoutAdapter;

    private UserInfoBean mPersonalDetail;

    private AliOSSCredentialBean aliOSSCredentialBean;

    private int type = 0;

    @Override
    public int getLayoutId() {
        return R.layout.activity_person_detial_edit;
    }

    @Override
    public void installViews() {

        setFullScreen(true);
        imgHeader = findViewById(R.id.photo_riv);
        findViewById(R.id.photo_riv).setOnClickListener(this);
        findViewById(R.id.left_layout).setOnClickListener(this);
        findViewById(R.id.img_camera).setOnClickListener(this);
        findViewById(R.id.tv_modify_bg).setOnClickListener(this);

        // 用户基础资料
        initUserInfo();

        // 获取用户信息
        getHttpData();

        // 签名
        getAliSign();
    }

    /**
     * 获取 ali oss 签名信息
     */
    public void getAliSign() {
        BizLayer.getInstance().getSystemModule().getAliSign(new AresSubscriber<AliOSSCredentialBean>() {
            @Override
            protected void onSuccess(AliOSSCredentialBean data) {
                aliOSSCredentialBean = data;
                ImageUpLoadUtils.getInstance().init(PersonalEditActivity.this, aliOSSCredentialBean);
                Log.e("", "TeacherRegisterPresenterImpl-->我获得了ali签名信息");
            }
        });
    }

    /**
     * 基础资料监听
     */
    private void initUserInfo() {
        RecyclerView recycler = findViewById(R.id.item_layout_rv);
        mPersonEditLayoutAdapter = new PersonEditLayoutAdapter();
        recycler.setLayoutManager(new LinearLayoutManager(mActivity));
        recycler.setAdapter(mPersonEditLayoutAdapter);
        // 基本资料
        mPersonEditLayoutAdapter.setOnItemClickListener((adapter, view, position) -> {
            PersonEditLayoutEntry itemLayoutEntry = (PersonEditLayoutEntry) adapter.getData().get(position);
            switch (itemLayoutEntry.getId()) {
                // 昵称
                case PersonEditLayoutEntry.TYPE_NICK_NAME:
                    EditInfoActivity.start(mActivity, EditInfoActivity.TYPE_NICKNAME, itemLayoutEntry.getContent(), RESULT_CODE_NICKNAME);
                    break;
                // 年龄
                case PersonEditLayoutEntry.TYPE_AGE: {
                    String content = itemLayoutEntry.getContent();
                    int year = 1990;
                    int month = 0;
                    int day = 1;
                    boolean isHappenCatch = false;
                    if (!TextUtils.isEmpty(content)) {
                        String[] split = content.split(mActivity.getString(R.string.str_space2));
                        if (split.length > 2) {
                            SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
                            try {
                                int[] yearMonthDay = DateUtils.getYearMonthDay(sf.parse(split[2]));
                                year = yearMonthDay[0];
                                month = yearMonthDay[1];
                                day = yearMonthDay[2];
                            } catch (ParseException e) {
                                e.printStackTrace();
                                isHappenCatch = true;
                            }
                        } else {
                            isHappenCatch = true;
                        }
                    } else {
                        isHappenCatch = true;

                    }
                    if (isHappenCatch) {
                        //发生了异常 说明 没有选择过年龄
                        Calendar defaultDate = Calendar.getInstance();
                        year = defaultDate.get(Calendar.YEAR) - 25;
                        month = defaultDate.get(Calendar.MONTH);
                        day = defaultDate.get(Calendar.DAY_OF_MONTH);
                    }

                    //时间选择
                    TimePickerViewManager mTimeManager = TimePickerViewManager.getInstance(this);
                    Calendar selectDate = Calendar.getInstance();
                    try {
                        selectDate.set(year, month, day);
                    } catch (Exception e) {
                        e.printStackTrace(); //防止设置时发生平年 闰年问题
                        selectDate.set(year, month, day > 1 ? day - 1 : day);
                    }
                    mTimeManager.setSelectCalendar(selectDate);

                    int endyear = 2024;
                    int endMonth = 1;
                    int endDay = 1;

                    int startYear = 1970;
                    try {
                        String date = DateUtils.formatTime(DateUtils.getNowTimeStamp(), DateUtils.FORMAT);
                        String[] split = date.split("-");
                        endyear = Integer.parseInt(split[0]);
                        startYear = endyear - 99;
                        endyear = endyear - 18;
                        endMonth = Integer.parseInt(split[1]);
                        endDay = Integer.parseInt(split[2]);
                    } catch (Exception ignored) {

                    }
                    Calendar startDate = Calendar.getInstance();
                    startDate.set(startYear, 0, 1);
                    Calendar endDate = Calendar.getInstance();
                    endDate.set(endyear, endMonth - 1, endDay);
                    mTimeManager.initTimePickerView(mActivity, startDate, endDate, date -> {
                        String dateTime = DateUtils.getDateTime(date, "yyyy-MM-dd");
                        JSONObject json = new JSONObject();
                        json.put("birthday", dateTime);
                        BizLayer.getInstance().getAccountModule().editUserInfo(json, new AresSubscriber<Object>() {
                            @Override
                            protected void onSuccess(Object response) {
                                ToastUtil.showMessage(getString(R.string.edit_success));
                                mPersonEditLayoutAdapter.setData(position, new PersonEditLayoutEntry(PersonEditLayoutEntry.TYPE_AGE, "生日", "生日", dateTime));
                            }
                        });
                    });
                    mTimeManager.showTimePicmkerView();
                }
                break;
                // 签名
                case PersonEditLayoutEntry.TYPE_DESC:
                    EditInfoActivity.start(mActivity, EditInfoActivity.TYPE_AUTOGRAPH, itemLayoutEntry.getContent(), RESULT_CODE_AUTOGRAPH);
                    break;
                // 身高
                case PersonEditLayoutEntry.TYPE_HEIGHT:
                    setHeight(itemLayoutEntry.getContent());
                    break;
                // 体重
                case PersonEditLayoutEntry.TYPE_WEIGHT:
                    setWeight(itemLayoutEntry.getContent());
                    break;
                // 地区
                case PersonEditLayoutEntry.TYPE_ADDRESS:
                    // 城市选择
                    CityPicker.from(PersonalEditActivity.this).enableAnimation(true).setAnimationStyle(R.style.DefaultCityPickerAnimation).setLocatedCity(null).setOnPickListener(new OnPickListener() {
                        @Override
                        public void onPick(int position, City data) {
                            mPersonEditLayoutAdapter.getData().get(6).setContent(data.getName());
                            BizLayer.getInstance().getAccountModule().editUserInfo("city", data.getCode(), new AresSubscriber<Object>() {
                                @Override
                                protected void onSuccess(Object response) {
                                    getHttpData();
                                }
                            });
                        }

                        @Override
                        public void onCancel() {

                        }

                        @Override
                        public void onLocate() {
                            new Handler().postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    BdLocationUtil.getInstance().requestLocation(new BdLocationUtil.MyLocationListener() {

                                        @Override
                                        public void myLocation(BDLocation location) {
                                            CityPicker.from(PersonalEditActivity.this).locateComplete(new LocatedCity(location.getCity(), location.getProvince(), location.getCityCode()), LocateState.SUCCESS);
                                        }
                                    });
                                }
                            }, 2000);
                        }
                    }).show();

                    break;
                // 职业
                case PersonEditLayoutEntry.TYPE_JOB:
                    EditInfoActivity.start(mActivity, EditInfoActivity.TYPE_JOB, itemLayoutEntry.getContent(), RESULT_CODE_JOB);
                    break;
                default:
                    break;
            }
        });
    }

    private void setHeight(String content) {

        List<String> listHeight = new ArrayList<>();
        for (int i = 50; i < 230; i++) {
            listHeight.add(i + "CM");
        }

        WhellPickerViewManager whellPickerViewManager = WhellPickerViewManager.getInstance(mActivity).builder(listHeight);
        if (!content.equals("")) {
            whellPickerViewManager.setDefault(content);
        }
        whellPickerViewManager.showPickerView();
        whellPickerViewManager.setOnCallOptionsListener(new WhellPickerViewManager.OnCallOptionsListener() {
            @Override
            public void callBackInfo(String sw1, String sw2) {
                BizLayer.getInstance().getAccountModule().editUserInfo("height", sw1, new AresSubscriber<Object>() {
                    @Override
                    protected void onSuccess(Object response) {
                        getHttpData();
                    }
                });
            }
        });
    }

    private void setWeight(String content) {

        List<String> listHeight = new ArrayList<>();
        for (int i = 40; i < 150; i++) {
            listHeight.add(i + "KG");
        }

        WhellPickerViewManager whellPickerViewManager = WhellPickerViewManager.getInstance(mActivity).builder(listHeight);
        if (!content.equals("")) {
            whellPickerViewManager.setDefault(content);
        }
        whellPickerViewManager.showPickerView();
        whellPickerViewManager.setOnCallOptionsListener(new WhellPickerViewManager.OnCallOptionsListener() {
            @Override
            public void callBackInfo(String sw1, String sw2) {
                BizLayer.getInstance().getAccountModule().editUserInfo("weight", sw1, new AresSubscriber<Object>() {
                    @Override
                    protected void onSuccess(Object response) {
                        getHttpData();
                    }
                });
            }
        });
    }

    public void getHttpData() {
        BizLayer.getInstance().getAccountModule().getUserFullInfo(RXingUtils.getUserId(), new AresSubscriber<UserInfoBean>() {
            @Override
            protected void onSuccess(UserInfoBean personalDetail) {
                mPersonalDetail = personalDetail;
                initData();
            }
        });
    }

    /**
     * 加载用户信息
     */
    public void initData() {
        List<PersonEditLayoutEntry> mItemList = new ArrayList<>();
        mItemList.add(new PersonEditLayoutEntry(PersonEditLayoutEntry.TYPE_NICK_NAME, "昵称", "昵称", mPersonalDetail.getNickName()));
        mItemList.add(new PersonEditLayoutEntry(PersonEditLayoutEntry.TYPE_DESC, "简介", "简介", mPersonalDetail.getIntro() == null ? "这个人很懒，什么都没有留下" : mPersonalDetail.getIntro()));
        mItemList.add(new PersonEditLayoutEntry(PersonEditLayoutEntry.TYPE_GENDER, "性别", "性别", mPersonalDetail.getGender() == 0 ? "男" : "女"));
        mItemList.add(new PersonEditLayoutEntry(PersonEditLayoutEntry.TYPE_AGE, "生日", "生日", mPersonalDetail.getBirthday()));
        mItemList.add(new PersonEditLayoutEntry(PersonEditLayoutEntry.TYPE_HEIGHT, "身高", "身高", mPersonalDetail.getHeight() == null ? "" : mPersonalDetail.getHeight()));
        mItemList.add(new PersonEditLayoutEntry(PersonEditLayoutEntry.TYPE_WEIGHT, "体重", "体重", mPersonalDetail.getWeight() == null ? "" : mPersonalDetail.getWeight()));
        mItemList.add(new PersonEditLayoutEntry(PersonEditLayoutEntry.TYPE_ADDRESS, "地区", "地区", mPersonalDetail.getCity() == null ? "" : mPersonalDetail.getCity()));
        mItemList.add(new PersonEditLayoutEntry(PersonEditLayoutEntry.TYPE_JOB, "职业", "职业", mPersonalDetail.getJob() == null ? "" : mPersonalDetail.getJob()));
        mPersonEditLayoutAdapter.setList(mItemList);
        ImageLoadUtil.loadAvatar(mActivity, mPersonalDetail.getAvatar(), imgHeader);
    }

    @Override
    public void onClick(View view) {
        super.onClick(view);
        if (view.getId() == R.id.left_layout) {
            // 页面关闭
            finish();
        } else if (view.getId() == R.id.photo_riv || view.getId() == R.id.img_camera) {
            // 头像替换
            type = 1;
            initPermission();

        } else if (view.getId() == R.id.tv_modify_bg) {
            type = 2;
            initPermission();
        }
    }

    /**
     * 权限初始化
     */
    private void initPermission() {

        List<String> permissions = new ArrayList<>();

        if (android.os.Build.VERSION.SDK_INT >= 33) {
            permissions.add(Manifest.permission.CAMERA);
            permissions.add(Manifest.permission.READ_MEDIA_AUDIO);
            permissions.add(Manifest.permission.READ_MEDIA_IMAGES);
            permissions.add(Manifest.permission.READ_MEDIA_VIDEO);
        } else {
            permissions.add(Manifest.permission.CAMERA);
            permissions.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
            permissions.add(Manifest.permission.READ_EXTERNAL_STORAGE);
        }

        PermissionsUtils.getInstance().checkPermission(mActivity, permissions, "修改照片", new PermissionsUtils.OnCallBackListener() {
            @Override
            public void open(List<String> list) {
                // 延迟0.5秒请求
                uploadAvatar();
            }

            @Override
            public void notOpen(List<String> list, String label) {
                ToastUtil.showMessage(getString(R.string.go_set_open_permission));
            }
        });
    }

    /**
     * 头像替换
     */
    private void uploadAvatar() {
        PictureSelector.create(mActivity).openGallery(SelectMimeType.ofImage()).setImageEngine(GlideImageEngine.Companion.getInstance()).setCompressEngine(McImageCompressEngine.Companion.getInstance()).setCropEngine(new DefaultCropFileEngine()).setMaxSelectNum(1).isDirectReturnSingle(true).isDisplayCamera(false).isOpenClickSound(false).isFastSlidingSelect(true).isPreviewFullScreenMode(true).isPreviewZoomEffect(true).isPreviewImage(true).isMaxSelectEnabledMask(true).isGif(false).forResult(PictureConfig.CHOOSE_REQUEST);
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case RESULT_CODE_NICKNAME:
                case RESULT_CODE_AUTOGRAPH:
                case RESULT_CODE_JOB:
                    getHttpData();
                    break;
                default:
                    break;
            }
        }

        if (requestCode == PictureConfig.CHOOSE_REQUEST) {
            if (data != null) {

                ArrayList<LocalMedia> result = PictureSelector.obtainSelectorList(data);
                String picturePath = result.get(0).getRealPath();


                if (aliOSSCredentialBean == null) {
                    runOnUiThread(() -> {
                        showToast("获取照片签名异常，请重新选择照片");
                        getAliSign();
                    });
                } else {

                    if (type == 1) {
                        ImageLoadUtil.loadAvatar(mActivity, picturePath, imgHeader);
                    }

                    showMProgress();

                    String time = System.currentTimeMillis() + ".png";

                    ImageUpLoadUtils.getInstance().asyncUpLoad(time, picturePath, new ImageUpLoadUtils.OnAsyncUpLoadListener() {

                        @Override
                        public void onProgress(PutObjectRequest request, long currentSize, long totalSize) {

                        }

                        @Override
                        public void onSuccess(PutObjectRequest request, PutObjectResult result, String directory) {
                            closeProgress();
                            String path = directory + request.getObjectKey();

                            JSONObject json = new JSONObject();
                            if (type == 1) {
                                json.put("avatar", path);
                            } else {
                                json.put("bgImage", path);
                            }
                            BizLayer.getInstance().getAccountModule().editUserInfo(json, new AresSubscriber<Object>() {
                                @Override
                                protected void onSuccess(Object response) {
                                    showToast("修改成功！");
                                }
                            });
                        }

                        @Override
                        public void onFailure(PutObjectRequest request, ClientException clientExcepion, ServiceException serviceException) {
                            showToast("上传失败");
                            Log.e("tag", request.toString());
                            Log.e("tag", serviceException.getMessage());
                            closeProgress();
                        }
                    });
                }
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        RxBus.getDefault().post(new PersonalRefresh());
    }
}